import Footer from '@/components/Footer';
import merchantManagerShopApi from '@/pages/MerchantManager/Shop/request';
import menuApi from '@/pages/Organization/RoleManagement/menu-request';
import userApi from '@/pages/Organization/UserManagement/request';
import * as icons from '@ant-design/icons';
import Icon, { ShopOutlined } from '@ant-design/icons';
import type { Settings as LayoutSettings } from '@ant-design/pro-components';
import type { RunTimeLayoutConfig } from '@umijs/max';
import { history } from '@umijs/max';
import { ConfigProvider } from 'antd';
import defaultSettings from '../config/defaultSettings';
import { userRotues } from '../config/routes';
import { AvatarDropdown, AvatarName } from './components/RightContent/AvatarDropdown';
import { loginPath, merchantLoginPath, merchantRoutePath } from './config';
import { errorConfig } from './requestErrorConfig';

export type InitialState = {
  settings?: Partial<LayoutSettings>;
  userInfo?: UserManagementApi.InfoResponse;
  loading?: boolean;
  getUserInfo: (params: UserManagementApi.InfoParams) => Promise<UserManagementApi.InfoResponse>;
  getMerchantUserInfo: (
    params: MerchantManagerShopApi.UserInfoParams,
  ) => Promise<MerchantManagerShopApi.UserInfoResponse>;
  getAuthMenu: (
    params: MenuManagementApi.GetRelationParams,
  ) => Promise<MenuManagementApi.GetRelationResponse[]>;
};

// const isDev = process.env.NODE_ENV === 'development';
const getAuthMenu = async (params: MenuManagementApi.GetRelationParams) => {
  const data = await menuApi.getRelation(params);
  return data;
};
const getUserInfo = async (params: UserManagementApi.InfoParams) => {
  const userInfo = await userApi.getInfo(params);
  return userInfo;
};
const getMerchantUserInfo = async (params: MerchantManagerShopApi.UserInfoParams) => {
  const userInfo = await merchantManagerShopApi.getUserInfo(params);
  return userInfo;
};
export async function getInitialState(): Promise<InitialState> {
  const settings = defaultSettings as Partial<LayoutSettings>;
  const { location } = history;
  const id = window.localStorage.getItem('user_id');
  const state: InitialState = { settings, getUserInfo, getAuthMenu, getMerchantUserInfo };
  if (![loginPath, merchantLoginPath].includes(location.pathname) && id) {
    if (location.pathname.includes(merchantRoutePath)) {
      const userInfo = await getMerchantUserInfo({});
      Object.assign(state, { userInfo, authMenu: [] });
    } else {
      const userInfo = await getUserInfo({ id });
      if (userInfo) {
        const { roleDepartmentLists } = userInfo;
        if (roleDepartmentLists && roleDepartmentLists.length) {
          const roleDepartment = roleDepartmentLists[0];
          const { groupID, subsidiaryID, departmentId, userRoleId } = roleDepartment;
          Object.assign(userInfo, { groupID, subsidiaryID, departmentId, userRoleId });
        }

        const authMenu = await getAuthMenu({ RoleId: userInfo.userRoleId });
        Object.assign(state, { userInfo, authMenu });
        window.localStorage.setItem('user_info', JSON.stringify(userInfo));
      }
    }

    return state;
  } else {
    return state;
  }
}

export const layout: RunTimeLayoutConfig = ({ initialState }) => {
  return {
    actionsRender: () => [],
    avatarProps: {
      src: 'https://gw.alipayobjects.com/zos/rmsportal/BiazfanxmamNRoxxVxka.png',
      title: <AvatarName />,
      render: (_, avatarChildren) => {
        return <AvatarDropdown>{avatarChildren}</AvatarDropdown>;
      },
    },
    waterMarkProps: {
      // content: '',
    },
    footerRender: () => <Footer />,
    onPageChange: async () => {
      const { location } = history;

      if (
        !initialState?.userInfo &&
        location.pathname !== loginPath &&
        !location.pathname.includes(merchantRoutePath)
      ) {
        history.push(loginPath);
      }
    },
    layoutBgImgList: [
      {
        src: 'https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/D2LWSqNny4sAAAAAAAAAAAAAFl94AQBr',
        left: 85,
        bottom: 100,
        height: '303px',
      },
      {
        src: 'https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/C2TWRpJpiC0AAAAAAAAAAAAAFl94AQBr',
        bottom: -68,
        right: -45,
        height: '303px',
      },
      {
        src: 'https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/F6vSTbj8KpYAAAAAAAAAAAAAFl94AQBr',
        bottom: 0,
        left: 0,
        width: '331px',
      },
    ],
    menu: {
      locale: !location.pathname.includes(merchantRoutePath),
      request: async () => {
        const { location } = history;

        if (location.pathname.includes(merchantRoutePath)) {
          const data = await merchantManagerShopApi.getAllList();

          const routes = data.map((item) => ({
            path: `/merchant/shop/${item.shopId}`,
            name: `${item.shopName}`,
          }));
          const merchantMenu = [
            {
              name: '门店管理',
              path: '/merchant',
              // @ts-ignore
              icon: <ShopOutlined />,
              // access: 'merchant',
              routes,
            },
          ];
          return merchantMenu;
        } else {
          return userRotues.map((route) => ({
            ...route,
            // @ts-ignore
            icon: route.icon && <Icon component={icons[`${route.icon}Outlined`]} />,
          }));
        }
      },
    },
    menuHeaderRender: undefined,
    // 自定义 403 页面
    // unAccessible: <div>unAccessible</div>,
    // 增加一个 loading 的状态
    childrenRender: (children) => {
      // if (initialState?.loading) return <PageLoading />;
      return (
        <ConfigProvider
          theme={{
            token: {
              borderRadius: 2,
              fontFamily: `Helvetica Neue, Helvetica, PingFang SC, Tahoma, Arial, sans-serif, -apple-system,
                          BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, 'Noto Sans',
                          'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', 'Noto Color Emoji'`,
            },
          }}
        >
          <div className="page-container-box">{children}</div>
        </ConfigProvider>
      );
    },
    ...initialState?.settings,
  };
};

/**
 * @name request 配置，可以配置错误处理
 * 它基于 axios 和 ahooks 的 useRequest 提供了一套统一的网络请求和错误处理方案。
 * @doc https://umijs.org/docs/max/request#配置
 */
export const request = {
  ...errorConfig,
};
